﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using GuRenFang.Service.Entity;
using GuRenFang.Service.IBiz;

namespace GuRenFang.Controllers.Management
{
    public class PictorialController : Controller
    {
        private readonly IPictorialCategoryBiz _service;

        public PictorialController(IPictorialCategoryBiz service)
        {
            _service = service;
        }

        [Authorize]
        public ActionResult PictorialCategoryList(int? page = 1)
        {
            ViewBag.Model = "Pictorial";

            short size = Convert.ToInt16(ConfigurationManager.AppSettings["AdminpageSize"]);

            int totalRecord = 0;
            IEnumerable<PictorialCategory> categorys = _service.GetCategoryByPages(out totalRecord,
                                                                                   pageIndex: page.GetValueOrDefault(),
                                                                                   pageSize: size, orderFiled: "");

            var item = new PageItem
                           {
                               CurrentPage = page.GetValueOrDefault(),
                               TotalRecords = totalRecord,
                               TotalPages = (totalRecord%size == 0) ? totalRecord/size : totalRecord/size + 1,
                               ControllerName = "Pictorial",
                               ActionName = "PictorialCategoryList"
                           };

            var viewModels = new Pager<PictorialCategory> {DataSource = categorys, Item = item};

            return View(viewModels);
        }

        [Authorize]
        [HttpPost]
        public ActionResult PictorialCategoryAdd(FormCollection forms)
        {
            if (forms != null && !string.IsNullOrEmpty(forms["txtCategoryName"]))
            {
                string categoryName = forms["txtCategoryName"].Trim();
                var category = new PictorialCategory {Name = categoryName, ThumbnailPath = "/images/NoPicture.jpg"};
                category.CreatedTime = DateTime.Now;
                _service.Create(category);

                var directoryInfo = new DirectoryInfo(Server.MapPath("~/UpFiles/写真/" + categoryName + "/"));
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                directoryInfo = new DirectoryInfo(Server.MapPath("~/UpFiles/写真/" + categoryName + "/Thumbnail/"));
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
            }

            return RedirectToAction("PictorialCategoryList");
        }

        [Authorize]
        public ActionResult DeletePictorialCategory(int id, string name)
        {
            _service.Delete(id);

            Common.DeleteFolder(Server.MapPath("~/UpFiles/写真/" + name + "/"));

            return RedirectToAction("PictorialCategoryList");
        }

        [Authorize]
        public ActionResult ShowPictorialCategory(int id, string name)
        {
            if (id<=0 || string.IsNullOrEmpty(name))
            {
                return RedirectToAction("PictorialCategoryList");
            }

            ViewBag.Model = "Pictorial";
            ViewBag.CategoryId = id;
            PictorialCategory category = _service.GetById(id);
            ViewBag.ThumPath = category.ThumbnailPath;
            
            string categoryName = Server.UrlDecode(name);
            string filePath = "~/UpFiles/写真/" + categoryName + "/";
            ViewBag.Category = categoryName;
            ViewBag.Path = filePath;
            List<string> model = Common.GetImages(Server.MapPath(filePath));
            return View(model);
        }

        [Authorize]
        public ActionResult DeletePictorialPicture(string name, string category, int categoryId)
        {
            ViewBag.Model = "Pictorial";
            string xPath = "~/UpFiles/写真/" + category + "/" + name;
            string thumbnailImage = "~/UpFiles/写真/" + category + "/Thumbnail/" + name;

            DeleteFile(Server.MapPath(xPath));
            DeleteFile(Server.MapPath(thumbnailImage));
           
            return RedirectToAction("ShowPictorialCategory", new {id = categoryId, name = category});
        }

        private void DeleteFile(string xPath)
        {
            var pictorialInfo = new FileInfo(xPath);
            if (pictorialInfo.Exists)
            {
                pictorialInfo.Delete();
            }
        }


        [Authorize]
        public ActionResult SetAsFrontCover(string name, int categoryId)
        {
            PictorialCategory category = _service.GetById(categoryId);
            category.ThumbnailPath = "/UpFiles/写真/" + category.Name + "/Thumbnail/" + name;
            _service.Update(category);

            return RedirectToAction("PictorialCategoryList");
        }


        [ChildActionOnly]
        //[OutputCache(Duration = 3600)]
        public PartialViewResult _categoryAdmin(string photoType)
        {
            ViewBag.PhotoType = photoType;


            return PartialView("_categoryAdmin", _service.GetAll());
        }

       
        
    }

    public static class Common
    {
        public static void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir))
            {
                foreach (string fileSystemEntry in Directory.GetFileSystemEntries(dir))
                {
                    if (System.IO.File.Exists(fileSystemEntry))
                    {
                        System.IO.File.Delete(fileSystemEntry);
                    }
                    else
                    {
                        DeleteFolder(fileSystemEntry);
                    }
                }
                Directory.Delete(dir, true);
            }
        }

        public static List<string> GetImages(string filePath)
        {
            var model = new List<string>();
            var directoryInfo = new DirectoryInfo(filePath);
            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                if (fileInfos.Any())
                {
                    model.AddRange(from fileInfo in fileInfos where fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".gif" || fileInfo.Extension.ToLower() == ".png" select fileInfo.Name);
                }
            }
            return model;
        }

    }


}
